package com.cscp.javastudy.juc.threaddemo;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * 计数器(加法)
 */
public class CyclicBarrierDemo1 {

    public static void main(String[] args) {

        /*
         * 集齐七颗龙珠召唤神龙
         */
        CyclicBarrier cyclicBarrier = new CyclicBarrier(9, ()->{
            System.out.println("召唤神龙成功");//不会打印出这句话，因为循环只有7次，必须要等到够9次才执行这句
        });

        for (int i = 1; i <= 7; i++) {
            final int temp = i;
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+"收集"+temp+"个龙珠");
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }, String.valueOf(i)).start();
        }
    }
}
